import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, FlatList, Image, Alert, RefreshControl } from 'react-native';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import Ionicons from 'react-native-vector-icons/Ionicons';
import AsyncStorage from '@react-native-async-storage/async-storage';

const ShelfMain = ({ navigation }) => {
    const [bookshelf, setBookshelf] = useState([]);
    const [search, setSearch] = useState('');
    const [removeMode, setRemoveMode] = useState(false);
    const [refreshing, setRefreshing] = useState(false);
    const handleSearch = () => {
        if (searchQuery.trim()) {
            navigation.navigate('Search', { keyword: searchQuery.trim() });
            setSearchQuery(''); // 清空搜索框
        }
    };
    const fetchShelf = useCallback(async () => {
        try {
            const token = await AsyncStorage.getItem('authToken');
            const response = await fetch('http://124.222.104.145:8003/book/bookshelves/', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json',
                },
            });
            const data = await response.json();
            if (response.ok) {
                setBookshelf(data);
            } else {
                Alert.alert('获取失败', data.detail || '获取书架失败');
            }
        } catch (e) {
            Alert.alert('网络错误', '无法获取书架');
        }
    }, []);

    useEffect(() => {
        const checkToken = async () => {
            const token = await AsyncStorage.getItem('authToken');
            if (!token) {
                navigation.replace('LoginPage');
            }
        };
        checkToken();
    }, []);

    useEffect(() => {
        fetchShelf();
    }, [fetchShelf]);

    const filteredBooks = bookshelf.filter(item =>
        item.book.title.includes(search)
    );

    const removeFromShelf = async (bookId) => {
        try {
            const token = await AsyncStorage.getItem('authToken');
            console.log('当前页面token:', token);
            const response = await fetch(`http://124.222.104.145:8003/book/books/${bookId}/remove-from-shelf/`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json',
                },
            });
            const data = await response.json();
            if (response.ok && data.success) {
                Alert.alert('成功', data.message || '移除成功');
                // 刷新书架
                fetchShelf();
            } else {
                Alert.alert('失败', data.message || '移除失败');
            }
        } catch (e) {
            Alert.alert('网络错误', '移除失败');
        }
    };

    const onRefresh = async () => {
        setRefreshing(true);
        await fetchShelf();
        setRefreshing(false);
    };

    const renderItem = ({ item }) => (
        <View style={styles.bookContainer}>
            <TouchableOpacity
                style={{ alignItems: 'center' }}
                onPress={() => navigation.navigate('BookContent', { bookId: item.book.id })}
            >
                <Image source={{ uri: item.book.image }} style={styles.cover} />
                <Text style={styles.title} numberOfLines={1} ellipsizeMode="tail">{item.book.title}</Text>
                <Text style={styles.progress} numberOfLines={1} ellipsizeMode="tail">{item.book.readProgress}</Text>
            </TouchableOpacity>
            {removeMode && (
                <TouchableOpacity
                    style={{ marginTop: 4, backgroundColor: '#ffeaea', borderRadius: 4, paddingHorizontal: 8, paddingVertical: 2 }}
                    onPress={() => {
                        Alert.alert(
                            '确认移除',
                            `确定要将《${item.book.title}》移出书架吗？`,
                            [
                                { text: '取消', style: 'cancel' },
                                { text: '移除', style: 'destructive', onPress: () => removeFromShelf(item.book.id) }
                            ]
                        );
                    }}
                >
                    <Text style={{ color: '#d9534f', fontSize: 12 }}>移除</Text>
                </TouchableOpacity>
            )}
        </View>
    );

    return (
        <View style={styles.container}>
            {/* 顶部搜索栏 */}
            <View style={styles.header}>
                <TouchableOpacity onPress={() => setRemoveMode(!removeMode)}>
                    <FontAwesome name="trash" size={20} color={removeMode ? "#d9534f" : "#888"} style={{ marginRight: 10 }} />
                </TouchableOpacity>
                <View style={styles.searchBox}>
                    <FontAwesome name="search" size={18} color="#999" style={{ marginRight: 6 }} />
                    <TextInput
                        placeholder="书架书籍"
                        placeholderTextColor="#aaa"
                        style={{ flex: 1 }}
                        value={search}
                        onChangeText={setSearch}
                    />
                    {search ? (
                        <TouchableOpacity onPress={() => setSearch('')}>
                            <FontAwesome name="times-circle" size={16} color="#bbb" style={{ marginLeft: 6 }} />
                        </TouchableOpacity>
                    ) : null}
                </View>
            </View>

            <FlatList
                data={filteredBooks}
                numColumns={3}
                keyExtractor={(item) => item.id.toString()}
                renderItem={renderItem}
                contentContainerStyle={styles.bookList}
                ListEmptyComponent={<Text style={{ textAlign: 'center', color: '#aaa', marginTop: 40 }}>暂无书籍</Text>}
                refreshControl={
                    <RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#4CAF50']} />
                }
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: { flex: 1, backgroundColor: '#fff', paddingTop: 50 },
    header: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 15, marginBottom: 10 },
    searchBox: {
        flex: 1,
        flexDirection: 'row',
        backgroundColor: '#f2f2f2',
        borderRadius: 20,
        paddingHorizontal: 10,
        height: 40,
        alignItems: 'center',
        marginRight: 0,
    },
    switch: { color: '#333', marginHorizontal: 6 },
    bookList: { paddingHorizontal: 10 },
    bookContainer: {
        width: '30%',
        margin: '1.6%',
        alignItems: 'center',
        borderWidth: 1,          // Added border
        borderColor: '#f2f2f2',     // Light gray border color
        borderRadius: 4,         // Matching cover's border radius
        padding: 4,              // Add some inner spacing
        // Shadow properties
        boxShadow: '-5.5px 4px 3.4px 0px rgba(142, 142, 142, 0.51)',
    },
    cover: { width: 80, height: 100, borderRadius: 4, marginBottom: 5 },
    title: { fontSize: 14, color: '#333', marginBottom: 2, maxWidth: 80 },
    progress: { fontSize: 12, color: '#888', maxWidth: 80 },
});

export default ShelfMain;